package com.google.code.mochaccino.framework.hibernate;
/*
 * Copyright 2012 Claude Houle claude.houle@gmail.com
 *
 * Licensed under the Apache License, Version 2.0 (the "License");
 * you may not use this file except in compliance with the License.
 * You may obtain a copy of the License at
 *
 * http://www.apache.org/licenses/LICENSE-2.0
 *
 * Unless required by applicable law or agreed to in writing, software
 * distributed under the License is distributed on an "AS IS" BASIS,
 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
 * See the License for the specific language governing permissions and
 * limitations under the License.
 */

import javax.inject.Inject;
import javax.validation.Validation;
import javax.validation.Validator;
import javax.validation.ValidatorFactory;
import org.hibernate.Session;
import org.hibernate.SessionFactory;

/**
 * Session Provider Implementation that assume that the transaction is already started
 * before even starting to be used. This means that in a non-transaction code, this should break.
 */
public final class SessionProvider {

	/** Session Factory */
	private SessionFactory factory;

	/** Validator Factory */
	private ValidatorFactory validatorFactory;

	/** Constructor */
	public SessionProvider( SessionFactory factory ) {
		this( factory, Validation.buildDefaultValidatorFactory() );
	}

	/** Constructor */
	@Inject
	public SessionProvider( SessionFactory factory, ValidatorFactory validatorFactory ) {
		this.factory = factory;
		this.validatorFactory = validatorFactory;
	}

	/**
	 * Return the Existing Session.
	 * <p/>
	 * Note that the behavior of this method is subject to the configuration of the session factory
	 * and it's session management context. In a JTASessionContext, if the transaction is properly started,
	 * it will always return the same session.
	 * <p/>
	 * For others implementation, this may not be so simple.
	 * </p>
	 */
	public Session getSession() {
		if ( factory.isClosed() ) {
			throw new RuntimeException( "Session Factory is closed... Cannot proceed further" );
		}

		return factory.getCurrentSession();
	}

	/** Return the validator */
	public Validator getValidator() {
		if ( factory.isClosed() ) {
			throw new RuntimeException( "Session Factory is closed... Cannot proceed further" );
		}

		if ( validatorFactory == null ) {
			return null;
		}

		return validatorFactory.getValidator();
	}

}
